import hashlib
trans_5C = bytes((x ^ 0x5C) for x in range(256))
trans_36 = bytes((x ^ 0x36) for x in range(256))
# hmac-sha256加密算法类
class HMACSha256:
    blocksize = 64  # 512-bit HMAC; can be changed in subclasses.
    __slots__ = ("_digest_cons", "_inner", "_outer", "block_size", "digest_size")
    def __init__(self, key, msg):
        self._outer = hashlib.sha256()
        self._inner = hashlib.sha256()
        self.digest_size = self._inner.digest_size
        if hasattr(self._inner, 'block_size'):
            blocksize = self._inner.block_size
            if blocksize < 16:
                blocksize = self.blocksize
        else:
            blocksize = self.blocksize
        self.block_size = blocksize
        if len(key) > blocksize:
            key = hashlib.sha256(key).digest()
        key = key.ljust(blocksize, b'\0')
        self._outer.update(key.translate(trans_5C))
        self._inner.update(key.translate(trans_36))
        if msg is not None:
            self.update(msg)
    def update(self, msg):
        self._inner.update(msg)
    def digest(self):
        h = self._outer.copy()
        h.update(self._inner.digest())
        return h.digest()
    def hexdigest(self):
        h = self._outer.copy()
        h.update(self._inner.digest())
        return h.hexdigest()
